package com.personal.dao.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;

import com.personal.dao.exception.TransactionException;

/**
 * Jdbc工具类
 * @author cuibo
 *
 */
public class JdbcUtil
{
    private static final Log LOG = LogFactory.getLog(JdbcUtil.class);
    
    /**
     * 获取连接
     * @param template
     * @return
     */
    public static Connection getConnection(JdbcTemplate template)
    {
        return DataSourceUtils.getConnection(template.getDataSource());
    }
    
    /**
     * 判断连接是否开启事务
     * @param con
     * @param template
     * @return
     */
    public static boolean isConnectionTransactional(Connection con, JdbcTemplate template)
    {
        return DataSourceUtils.isConnectionTransactional(con, template.getDataSource());
    }
    
    /**
     * 开启事务
     * @param con
     */
    public static void begainTransaction(Connection con)
    {
        try
        {
            con.setAutoCommit(false);
        } catch (SQLException e)
        {
            LOG.error(e);
            throw new TransactionException(e.getMessage(), e);
        }
    }
    
    /**
     * 回滚事务
     * @param con
     */
    public static void rollbackTransaction(Connection con)
    {
        try
        {
            con.rollback();
        } catch (SQLException e)
        {
            LOG.error(e);
            throw new TransactionException(e.getMessage(), e);
        }
    }
    
    /**
     * 提交事务
     * @param con
     */
    public static void commitTransaction(Connection con)
    {
        try
        {
            con.commit();
        } catch (SQLException e)
        {
            LOG.error(e);
            throw new TransactionException(e.getMessage(), e);
        }
    }
    
    /**
     * 资料释放
     * @param template
     * @param conn
     * @param st
     * @param rs
     */
    public static void releaseResource(JdbcTemplate template, Connection conn, Statement st, ResultSet rs)
    {
        if (rs != null)
        {
            try
            {
                rs.close();
            } catch (SQLException e)
            {
                LOG.error(e);
            }
        }

        if (st != null)
        {
            try
            {
                st.close();
            } catch (SQLException e)
            {
                LOG.error(e);
            }
        }
        DataSourceUtils.releaseConnection(conn, template.getDataSource());
    }
}
